package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.service.RedisService;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.entity.Cart;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    RedisService redisService;

    @Override
    public void saveOrUpdate(Cart cart) {
        redisService.hset(getCartkey(),String.valueOf(cart.getDishesId()), JSONUtil.toJsonStr(cart));
    }

    @Override
    public List<Cart> list() {
        return  redisService.hvals(getCartkey())
                .stream().map(i->JSONUtil.toBean(i,Cart.class)).toList();

    }

    @Override
    public void delete(List<String> ids) {
        redisService.hdel(getCartkey(),ids.toArray(new String[]{}));

    }

    private  String getCartkey(){
        return CommonConstant.CART_KEY_PREFIX+ LoginUserContext.getUserId();
    }
}
